$(function() {
	$.ajax({
		sync: true
	});
	//显示数值发生变化时按条数查询
	$('#pageSize').change(function() {
		$('#ubody').html('');
		dataPage(1,"");
	});
	$("#searchBtn").click(function() {
		var keyword = $("#keyword").val();
		dataPage(1, keyword);
	});

	//搜索输入框回车事件
	$("#keyword").keydown(function(e) {
		if(e.keyCode == 13) {
			$('#searchBtn').click();
		}
	});

	var dataPage = function(cpage,keyword) {
		$('#ubody').html('');
		var pageSize = $("#pageSize option:selected").text();
		$.ajax({
			url: '/api/user?',
			type: 'GET',
			data: {'cpage':cpage, 'pageSize':pageSize, 'keyword':keyword, '_t':new Date().getTime()},
			success: function(data) {
				// console.info('dataaaa:',data);
				var udata = {};
				if(data == 'noPrivilege'){
					udata = {count:0,data:[]};
				} else {
					udata = data;
				}
				var page;
				// $("#showCount").html("共"+ udata.count + "条记录");
				if (udata.count < pageSize) {
					page = 1;
				} else {
					page = Math.ceil(udata.count / pageSize);
				}

				var options = {
					currentPage: cpage,
					totalPages: page,
					alignment: 'right',
					count:udata.count,
					selectorId: 'pageSeletct',
					onPageChanged: function(e, oldPage, newPage) {
						dataPage(newPage, keyword);
					}
				};
				showData(udata.data, cpage, pageSize, udata.count);
				$('#paginator').bootstrapPaginator(options);
				$("#pageSeletct").change(function() {
					var page = $("#pageSeletct option:selected").val();
					$('#paginator').bootstrapPaginator("show",page);
				});

			},
			error: function(result) {
				alert('error');
			}

		});
	};

	//将查询到的数据显示
	var showData = function(data, cpage, pageSize, count) {
		// console.info('data:', data);
		$('#ubody').append('');
		if (data.length == 0) {
			$('#tip').html("<div class='alert alert-warning' style='margin-top:-20px;'>未能搜索到相关员工信息</div>");
			return;
		} else {
			$('#tip').html('');
		}

		for (var i = 0; i < data.length; i++) {
			var users = {
				username: data[i].userName,
				userId: data[i].id,
				password: data[i].password,
				employeeId: data[i].employeeId,
				employeeName: data[i].name,
				roleId: data[i].rid,
				roleName: data[i].roleName
			}; //定义users，存放用户、角色、type用于判定是增加还是修改

			var modal = "<tr><td class='center'>{{username}}<input type=hidden id=userId value={{userId}}><input type=hidden id=employeeId value={{employeeId}}><input type=hidden id=employeeName value={{employeeName}}><input type=hidden id=roleId value={{roleId}}><input type=hidden id=password value={{password}}><input type=hidden id=roleName value={{roleName}}><input type=hidden id=username value={{username}}></td><td class='center'>{{employeeName}}</td><td class='center'>{{roleName}}</td><td class='center'><i id='editIcon' style='cursor:pointer;' name='editIcon' class='icon-pencil bigger-150'></i>&nbsp;&nbsp;&nbsp;<i id='deleteIcon' style='cursor:pointer;' name=deleteIcon class='icon-trash  bigger-150'></i></td></tr>";
			var $html = $(Mustache.to_html(modal, users));
			$('#ubody').append($html);
			//定义编辑按钮编辑事件
			$html.find('#editIcon').click({
				html: $html
			}, function(e) {
				$('#userAdd').modal('show');
				var $html = $(e.data.html);
				var username = $html.find('#username').val();
				var password = $html.find('#password').val();
				var employeeName = $html.find('#employeeName').val();
				var employeeId = $html.find('#employeeId').val();
				var userId = $html.find('#userId').val();
				var roleName = $html.find('#roleName').val();
				var role = roleName.split(',');

				//将相应的信息存放在页面
				$('#userName').val(username);
				$('#pass').val(password);
				$('#employee').val(employeeName);
				$('#employeeId').val(employeeId);
				$('#userId').val(userId);

				var udata = {
					role: role,
					userId: userId,
					username: username,
					password: password,
					employeeId: employeeId
				}
				addUser(udata, cpage, pageSize, count);
			});

			//删除事件
			$html.find('#deleteIcon').click({
				html: $html
			}, function(e) {
				var $html = $(e.data.html);
				var id = $html.find("#userId").val();
				bootbox.confirm("确定删除该用户信息吗？", function(result) {
					// console.info(result);
					if (!result) {
						return;
					} else {
						$.ajax({
							url: '/api/user?id=' + id,
							type: 'delete',
							success: function(result) {
								if(result == 'noPrivilege'){
									bootbox.alert('您没有权限,操作失败！');
									return;
								}
								if((count % pageSize) == 1) {
									cpage = cpage - 1 ;
								}
								dataPage(cpage, "");
							},
							error: function(result) {
								// console.info(result);
								bootbox.alert("删除选项信息失败！", function() {
									dataPage(cpage, "");
									// window.location.href = '/usermanage';
								});
							}
						});
					}
				});
			});
		}
	};

	// $('#ubody').append('');
	dataPage(1, "");

	var availableTags = [];
	var getEmps = function() { //autocomplemete获取员工
		$.ajax({
			url: '/api/employee/all?',
			type: 'get',
			data: {'_t': new Date().getTime()},
			success: function(data) {
				if (data != "none") {
					for (var i = 0; i < data.length; i++) {
						var showStr = data[i].name + "-" + data[i].orgAddress + "-" + data[i].orgName;
						var item = {
							label: showStr,
							value: data[i].name,
							empId: data[i].id
						}
						availableTags.push(item);
					}
				}
				$("#employee").autocomplete({
					source: availableTags,
					select: function(event, ui) {
						$("#employeeId").val(ui.item.empId);
					}
				});
			}
		});
	};
	getEmps();

    //员工输入框光标移开事件
    $("#employee").blur(function(){
    	var empName = $("#employee").val().replace(/(^\s*)|(\s*$)/g, "");
    	var employeeId = $("#employeeId").val();
    	var hideName = $("#hideName").val();
    	if(empName == "") {
    		$("#employeeId").val("");
    		$("#hideName").val("");
    	}else{
    		$.ajax({
    			url: '/api/employee/getEmpByName?',
    			type: 'get',
    			data: {'empName': empName, '_t':new Date().getTime()},
    			success: function(result) {
    				// console.info("org---result:", result);
    				if(result != null && result.length != 0) {
    					if(employeeId == null || employeeId == "" || employeeId == 0) {
    						$("#employeeId").val(result[0].id);
    					}else if(result[0].name != hideName) {
    						$("#employeeId").val(result[0].id);
    					}
    				}else{
    					$("#employeeMsg").html("员工不存在！");
    					$("#employeeMessage").css("display","block");
    					return;
    				}
    			}
    		});
    	}
    }); 

	//新增加用户
	$('#ubtn').click(function() {
		//清除可能在修改时添加进标签的数据
		$('#userName').val('');
		$('#pass').val('');
		$('#employee').val('');
		$('#employeeId').val('');
		$('#selectRole').val('');
		$('#userId').val('');
		$('#userAdd').modal('show');
		var count = $("#showCount").html();
		var cpage = $("#pageSeletct option:selected").val();
		var pageSize = $("#pageSize option:selected").text();
		addUser(null, cpage, pageSize, parseInt(count));
	});

	var addUser = function(uudata, cpage, pageSize, count) {
		$("#nameMsg").html("");
		$("#passMsg").html("");
		$("#employeeMsg").html("");
		$("#roleMsg").html("");
		addRolelist(uudata);
		
		var type = '';
		if (uudata == null) {
			$('#myModalLabel1').html('添加用户');
			type = 'POST';
		} else {
			$('#myModalLabel1').html('编辑用户');
			type = 'PUT';
		}

		$('#userAddSave').unbind('click');
		$('#userAddSave').bind('click', function() {
			var username = $('#userName').val();
			var password = $('#pass').val();
			var employeeId = $('#employeeId').val();
			var userId = $('#userId').val(); //新增用户时，此取值为空，未使用

			var $label = $('#roleUser').find("label");
			var roles = [];

			//拿到选取的角色
			$.each($label, function(i, element) {
				var checked = $(element).find('input').is(':checked');
				if (checked) {
					var role = $(element).find('#roleId').val();
					roles.push(role);
				}

			});
			// console.info('roles:', roles);
			var userData = {
				userId: userId,
				userName: username,
				password: password,
				employeeId: employeeId,
				role: roles
			};
			if (userData.userName == '' || userData.userName == undefined) {
				$("#nameMsg").html("请填写用户名");
				$("#nameMessage").css('display','block');
				return;
			}else if(userData.userName.length<4){
				$("#nameMsg").html("用户名长度不能小于4");
				$("#nameMessage").css('display','block');
				return;
			}else{
				$("#nameMessage").css('display', 'none');
			}

			if (userData.password == '' || userData.password == undefined) {
				$("#passMsg").html("请填写密码");
				$("#passMessage").css('display','block');
				return;
			}else{
				$("#passMessage").css('display', 'none');
			}
			// console.info('userData.employeeId', userData.employeeId);

			if (userData.employeeId == '' || userData.employeeId == null ) {
				$("#employeeMsg").html("请填写员工");
				$("#employeeMessage").css('display','block');
				return;
			}else{
				$("#employeeMessage").css('display', 'none');
			}

			if (roles.length==0) {
				$("#roleMsg").html("请至少选择一个角色");
				$("#roleTip").css('display','block');
				return;
			}else{
				$("#roleTip").css('display', 'none');
			}
			
			

			// console.info('userData', userData);

			$.ajax({
				url: '/api/user/' + userData.userName + '?',
				type: 'GET',
				data: {'_t':new Date().getTime()},
				success: function(data) {
					//console.info('dadadada',data);
					if (data.length == 0 || data[0].id == userData.userId) {
						$.ajax({
							url: '/api/user',
							type: type,
							data: userData,
							success: function(data) {
								if(data == 'noPrivilege'){
									bootbox.alert('您没有权限,操作失败！');
									return;
								}
								if (type === 'POST') {
									bootbox.alert('用户添加成功！', function() {
										cpage = Math.ceil(count / pageSize);
										if((count % pageSize) == 0) {
											cpage = cpage + 1;
										}
										dataPage(cpage, "");
										// window.location.href = '/usermanage';
									});
									$('#userAdd').modal('hide');
								} else if (type === 'PUT') {
									bootbox.alert('用户更新成功！', function() {
										// window.location.href = '/usermanage';
										dataPage(cpage, "");
									});
									$('#userAdd').modal('hide');
								}
							},
							error: function(error) {
								if (type === 'POST') {
									bootbox.alert('用户添加失败！', function() {
										cpage = Math.ceil(count / pageSize);
										dataPage(cpage, "");
										// window.location.href = '/usermanage';
									});
								} else if (type === 'PUT') {
									bootbox.alert('用户更新失败！', function() {
										dataPage(cpage, "");
										// window.location.href = '/usermanage';
									});
								}
							}
						});
					} else {
						$("#nameMsg").html("该用户已存在！");
						$("#nameMessage").css('display','block');
					}
				},
				error: function() {
					if (type === 'POST') {
						bootbox.alert('用户添加失败！', function() {
							window.location.href = '/usermanage';
						});
					} else if (type === 'PUT') {
						bootbox.alert('用户更新失败！', function() {
							window.location.href = '/usermanage';
						});
					}
				}
			});
		});
	};



	//增加用户时增加角色列表或更新角色列表
	var addRolelist = function(userData) {

		$('#roleUser').html('');
		var template = "<label><input type=checkbox id='roleId' value={{roleId}}><span class=lbl></span><span id='roleGet'>{{role}}</span></label>&nbsp;&nbsp;&nbsp;";
		var template2 = "<label><input type=checkbox id='roleId' value={{roleId}} disabled='disabled' checked='true'/><span class=lbl></span><span id='roleGet'>{{role}}</span></label>&nbsp;&nbsp;&nbsp;";
		$.get('/api/role', function(data, status) {

			if (status == 'success') {
				$.each(data, function(i, role) {
					var pdata = {
						role: role.roleName,
						roleId: role.id
					};
					var $html = $(Mustache.to_html(template, pdata));
					if(role.roleName=="被考核人"){
						$html = $(Mustache.to_html(template2, pdata));
					}

					
					$('#roleUser').append($html);

					if (userData != null) {
						$.each(userData.role, function(i, urole) {
							if (pdata.role == urole) {
								$html.find('input').attr("checked", true);
							}
						});
					}
				});
			}
		});
	};
});